All files / web/src/app/arcade-rooms/[roomId] page.tsx

0% Statements 0/723
0% Branches 0/1
0% Functions 0/1
0% Lines 0/723

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import { css } from '../../../../styled-system/css'
import { useToast } from '@/components/common/ToastContext'
import { PageWithNav } from '@/components/PageWithNav'
import { useUserId } from '@/hooks/useUserId'
import { getRoomDisplayWithEmoji } from '@/utils/room-display'

interface Room {
  id: string
  code: string
  name: string | null
  gameName: string
  status: 'lobby' | 'playing' | 'finished'
  createdBy: string
  creatorName: string
  isLocked: boolean
}

interface Member {
  id: string
  userId: string
  displayName: string
  isCreator: boolean
  isOnline: boolean
  joinedAt: Date
}

interface Player {
  id: string
  userId: string
  name: string
  emoji: string
  color: string
  isActive: boolean
}

export default function RoomDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { showError } = useToast()
  const roomId = params.roomId as string
  const { data: userId } = useUserId()

  const [room, setRoom] = useState<Room | null>(null)
  const [members, setMembers] = useState<Member[]>([])
  const [memberPlayers, setMemberPlayers] = useState<Record<string, Player[]>>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [socket, setSocket] = useState<Socket | null>(null)
  const [isConnected, setIsConnected] = useState(false)

  useEffect(() => {
    fetchRoom()
  }, [roomId])

  useEffect(() => {
    if (!userId || !roomId) return

    // Connect to socket
    const sock = createSocket()
    setSocket(sock)

    sock.on('connect', () => {
      setIsConnected(true)
      // Join the room
      sock.emit('join-room', { roomId, userId: userId })
    })

    sock.on('disconnect', () => {
      setIsConnected(false)
    })

    sock.on('room-joined', (data) => {
      console.log('Joined room:', data)
      if (data.members) {
        setMembers(data.members)
      }
      if (data.memberPlayers) {
        setMemberPlayers(data.memberPlayers)
      }
    })

    sock.on('member-joined', (data) => {
      console.log('Member joined:', data)
      if (data.members) {
        setMembers(data.members)
      }
      if (data.memberPlayers) {
        setMemberPlayers(data.memberPlayers)
      }
    })

    sock.on('member-left', (data) => {
      console.log('Member left:', data)
      if (data.members) {
        setMembers(data.members)
      }
      if (data.memberPlayers) {
        setMemberPlayers(data.memberPlayers)
      }
    })

    sock.on('room-error', (error) => {
      console.error('Room error:', error)
      setError(error.error)
    })

    sock.on('room-players-updated', (data) => {
      console.log('Room players updated:', data)
      if (data.memberPlayers) {
        setMemberPlayers(data.memberPlayers)
      }
    })

    return () => {
      sock.emit('leave-room', { roomId, userId: userId })
      sock.disconnect()
    }
  }, [roomId, userId])

  // Notify room when window regains focus (user might have changed players in another tab)
  useEffect(() => {
    if (!socket || !userId || !roomId) return

    const handleFocus = () => {
      console.log('Window focused, notifying room of potential player changes')
      socket.emit('players-updated', { roomId, userId: userId })
    }

    window.addEventListener('focus', handleFocus)
    return () => window.removeEventListener('focus', handleFocus)
  }, [socket, roomId, userId])

  const fetchRoom = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/arcade/rooms/${roomId}`)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }
      const data = await response.json()
      setRoom(data.room)
      setMembers(data.members || [])
      setMemberPlayers(data.memberPlayers || {})
      setError(null)
    } catch (err) {
      console.error('Failed to fetch room:', err)
      setError('Failed to load room')
    } finally {
      setLoading(false)
    }
  }

  const startGame = () => {
    if (!room) return
    // Navigate to the room game page
    router.push('/arcade')
  }

  const joinRoom = async () => {
    try {
      const response = await fetch(`/api/arcade/rooms/${roomId}/join`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ displayName: 'Player' }),
      })

      if (!response.ok) {
        const errorData = await response.json()

        // Handle specific room membership conflict
        if (errorData.code === 'ROOM_MEMBERSHIP_CONFLICT') {
          showError('Already in Another Room', errorData.userMessage || errorData.message)
          // Refresh the page to update room state
          await fetchRoom()
          return
        }

        throw new Error(errorData.error || `HTTP ${response.status}`)
      }

      const data = await response.json()

      // Show notification if user was auto-removed from other rooms
      if (data.autoLeave) {
        console.log(`[Room Join] ${data.autoLeave.message}`)
        // Could show a toast notification here in the future
      }

      // Refresh room data to update membership UI
      await fetchRoom()
    } catch (err) {
      console.error('Failed to join room:', err)
      showError('Failed to join room', err instanceof Error ? err.message : undefined)
    }
  }

  const leaveRoom = async () => {
    try {
      const response = await fetch(`/api/arcade/rooms/${roomId}/leave`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || `HTTP ${response.status}`)
      }

      // Navigate to arcade home after successfully leaving
      router.push('/arcade')
    } catch (err) {
      console.error('Failed to leave room:', err)
      showError('Failed to leave room', err instanceof Error ? err.message : undefined)
    }
  }

  if (loading) {
    return (
      <PageWithNav>
        <div
          className={css({
            minH: 'calc(100vh - 80px)',
            bg: 'linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #2d1b69 100%)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            fontSize: 'xl',
          })}
        >
          Loading room...
        </div>
      </PageWithNav>
    )
  }

  if (error || !room) {
    return (
      <PageWithNav>
        <div
          className={css({
            minH: 'calc(100vh - 80px)',
            bg: 'linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #2d1b69 100%)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            p: '8',
          })}
        >
          <div
            className={css({
              bg: 'rgba(255, 255, 255, 0.05)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              rounded: 'lg',
              p: '12',
              textAlign: 'center',
              maxW: '500px',
            })}
          >
            <p className={css({ fontSize: 'xl', color: 'white', mb: '4' })}>
              {error || 'Room not found'}
            </p>
            <button
              onClick={() => router.push('/arcade-rooms')}
              className={css({
                px: '6',
                py: '3',
                bg: '#3b82f6',
                color: 'white',
                rounded: 'lg',
                fontWeight: 600,
                cursor: 'pointer',
                _hover: { bg: '#2563eb' },
              })}
            >
              Back to Rooms
            </button>
          </div>
        </div>
      </PageWithNav>
    )
  }

  const onlineMembers = members.filter((m) => m.isOnline)

  // Check if current user is a member
  const isMember = members.some((m) => m.userId === userId)

  // Calculate union of all active players in the room
  const allPlayers: Player[] = []
  const playerIds = new Set<string>()

  for (const userId in memberPlayers) {
    for (const player of memberPlayers[userId]) {
      if (!playerIds.has(player.id)) {
        playerIds.add(player.id)
        allPlayers.push(player)
      }
    }
  }

  return (
    <PageWithNav>
      <div
        className={css({
          minH: 'calc(100vh - 80px)',
          bg: 'linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #2d1b69 100%)',
          p: '8',
        })}
      >
        <div className={css({ maxW: '1000px', mx: 'auto' })}>
          {/* Header */}
          <div
            className={css({
              bg: 'rgba(255, 255, 255, 0.05)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              rounded: 'lg',
              p: '8',
              mb: '6',
            })}
          >
            <div className={css({ mb: '4' })}>
              <button
                onClick={() => router.push('/arcade-rooms')}
                className={css({
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '2',
                  color: '#a0a0ff',
                  fontSize: 'sm',
                  cursor: 'pointer',
                  _hover: { color: '#60a5fa' },
                  mb: '3',
                })}
              >
                ← Back to Rooms
              </button>
            </div>
            <div
              className={css({
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                mb: '4',
              })}
            >
              <div>
                <h1
                  className={css({
                    fontSize: '3xl',
                    fontWeight: 'bold',
                    color: 'white',
                    mb: '2',
                  })}
                >
                  {getRoomDisplayWithEmoji({
                    name: room.name,
                    code: room.code,
                    gameName: room.gameName,
                  })}
                </h1>
                <div
                  className={css({
                    display: 'flex',
                    gap: '4',
                    color: '#a0a0ff',
                    fontSize: 'sm',
                  })}
                >
                  <span>🎮 {room.gameName}</span>
                  <span>👤 Host: {room.creatorName}</span>
                  <span
                    className={css({
                      px: '3',
                      py: '1',
                      bg: 'rgba(255, 255, 255, 0.1)',
                      color: '#fbbf24',
                      rounded: 'full',
                      fontWeight: 600,
                      fontFamily: 'monospace',
                    })}
                  >
                    Code: {room.code}
                  </span>
                </div>
              </div>
              <div
                className={css({
                  display: 'flex',
                  gap: '3',
                  alignItems: 'center',
                })}
              >
                <div
                  className={css({
                    display: 'flex',
                    alignItems: 'center',
                    gap: '2',
                    px: '3',
                    py: '2',
                    bg: isConnected ? 'rgba(16, 185, 129, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                    border: `1px solid ${isConnected ? '#10b981' : '#ef4444'}`,
                    rounded: 'full',
                  })}
                >
                  <div
                    className={css({
                      w: '2',
                      h: '2',
                      bg: isConnected ? '#10b981' : '#ef4444',
                      rounded: 'full',
                    })}
                  />
                  <span
                    className={css({
                      color: isConnected ? '#10b981' : '#ef4444',
                      fontSize: 'sm',
                    })}
                  >
                    {isConnected ? 'Connected' : 'Disconnected'}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Game Players - Union of all active players */}
          <div
            className={css({
              bg: 'rgba(255, 255, 255, 0.05)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              rounded: 'lg',
              p: '8',
              mb: '6',
            })}
          >
            <h2
              className={css({
                fontSize: '2xl',
                fontWeight: 'bold',
                color: 'white',
                mb: '2',
              })}
            >
              🎯 Game Players ({allPlayers.length})
            </h2>
            <p className={css({ color: '#a0a0ff', fontSize: 'sm', mb: '4' })}>
              These players will participate when the game starts
            </p>
            {allPlayers.length > 0 ? (
              <div className={css({ display: 'flex', gap: '2', flexWrap: 'wrap' })}>
                {allPlayers.map((player) => (
                  <div
                    key={player.id}
                    className={css({
                      display: 'flex',
                      alignItems: 'center',
                      gap: '2',
                      px: '3',
                      py: '2',
                      bg: 'rgba(59, 130, 246, 0.15)',
                      border: '2px solid rgba(59, 130, 246, 0.4)',
                      rounded: 'lg',
                      color: '#60a5fa',
                      fontWeight: 600,
                    })}
                  >
                    <span className={css({ fontSize: 'xl' })}>{player.emoji}</span>
                    <span>{player.name}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div
                className={css({
                  color: '#6b7280',
                  fontStyle: 'italic',
                  textAlign: 'center',
                  py: '4',
                })}
              >
                No active players yet. Members need to set up their players.
              </div>
            )}
          </div>

          {/* Members List */}
          <div
            className={css({
              bg: 'rgba(255, 255, 255, 0.05)',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              rounded: 'lg',
              p: '8',
              mb: '6',
            })}
          >
            <h2
              className={css({
                fontSize: '2xl',
                fontWeight: 'bold',
                color: 'white',
                mb: '2',
              })}
            >
              👥 Room Members ({onlineMembers.length}/{members.length})
            </h2>
            <p className={css({ color: '#a0a0ff', fontSize: 'sm', mb: '4' })}>
              Users in this room and their active players
            </p>
            <div className={css({ display: 'grid', gap: '3' })}>
              {members.map((member) => {
                const players = memberPlayers[member.userId] || []
                return (
                  <div
                    key={member.id}
                    className={css({
                      display: 'flex',
                      flexDirection: 'column',
                      gap: '2',
                      p: '4',
                      bg: 'rgba(255, 255, 255, 0.05)',
                      border: '1px solid rgba(255, 255, 255, 0.1)',
                      rounded: 'lg',
                      opacity: member.isOnline ? 1 : 0.5,
                    })}
                  >
                    <div
                      className={css({
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                      })}
                    >
                      <div
                        className={css({
                          display: 'flex',
                          alignItems: 'center',
                          gap: '3',
                        })}
                      >
                        <div
                          className={css({
                            w: '3',
                            h: '3',
                            bg: member.isOnline ? '#10b981' : '#6b7280',
                            rounded: 'full',
                          })}
                        />
                        <span className={css({ color: 'white', fontWeight: 600 })}>
                          {member.displayName}
                        </span>
                        {member.isCreator && (
                          <span
                            className={css({
                              px: '2',
                              py: '1',
                              bg: 'rgba(251, 191, 36, 0.2)',
                              color: '#fbbf24',
                              rounded: 'full',
                              fontSize: 'xs',
                              fontWeight: 600,
                            })}
                          >
                            HOST
                          </span>
                        )}
                      </div>
                      <span className={css({ color: '#a0a0ff', fontSize: 'sm' })}>
                        {member.isOnline ? '🟢 Online' : '⚫ Offline'}
                      </span>
                    </div>
                    {players.length > 0 && (
                      <div
                        className={css({
                          display: 'flex',
                          gap: '2',
                          flexWrap: 'wrap',
                          ml: '6',
                        })}
                      >
                        <span
                          className={css({
                            color: '#a0a0ff',
                            fontSize: 'xs',
                            mr: '1',
                          })}
                        >
                          Players:
                        </span>
                        {players.map((player) => (
                          <span
                            key={player.id}
                            className={css({
                              px: '2',
                              py: '1',
                              bg: 'rgba(59, 130, 246, 0.2)',
                              color: '#60a5fa',
                              border: '1px solid rgba(59, 130, 246, 0.3)',
                              rounded: 'full',
                              fontSize: 'xs',
                              fontWeight: 600,
                            })}
                          >
                            {player.emoji} {player.name}
                          </span>
                        ))}
                      </div>
                    )}
                    {players.length === 0 && (
                      <div
                        className={css({
                          ml: '6',
                          color: '#6b7280',
                          fontSize: 'xs',
                          fontStyle: 'italic',
                        })}
                      >
                        No active players
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>

          {/* Actions */}
          <div className={css({ display: 'flex', gap: '4' })}>
            {isMember ? (
              <>
                <button
                  onClick={leaveRoom}
                  className={css({
                    flex: 1,
                    px: '6',
                    py: '4',
                    bg: 'rgba(255, 255, 255, 0.1)',
                    color: 'white',
                    rounded: 'lg',
                    fontWeight: 600,
                    cursor: 'pointer',
                    _hover: { bg: 'rgba(255, 255, 255, 0.15)' },
                  })}
                >
                  Leave Room
                </button>
                <button
                  onClick={startGame}
                  disabled={allPlayers.length < 1}
                  className={css({
                    flex: 2,
                    px: '6',
                    py: '4',
                    bg: allPlayers.length < 1 ? '#6b7280' : '#10b981',
                    color: 'white',
                    rounded: 'lg',
                    fontSize: 'xl',
                    fontWeight: 600,
                    cursor: allPlayers.length < 1 ? 'not-allowed' : 'pointer',
                    opacity: allPlayers.length < 1 ? 0.5 : 1,
                    _hover: allPlayers.length < 1 ? {} : { bg: '#059669' },
                  })}
                >
                  {allPlayers.length < 1
                    ? 'Waiting for players...'
                    : `🎮 Start Game (${allPlayers.length} players)`}
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={() => router.push('/arcade-rooms')}
                  className={css({
                    flex: 1,
                    px: '6',
                    py: '4',
                    bg: 'rgba(255, 255, 255, 0.1)',
                    color: 'white',
                    rounded: 'lg',
                    fontWeight: 600,
                    cursor: 'pointer',
                    _hover: { bg: 'rgba(255, 255, 255, 0.15)' },
                  })}
                >
                  Back to Rooms
                </button>
                <button
                  onClick={joinRoom}
                  disabled={room.isLocked}
                  className={css({
                    flex: 2,
                    px: '6',
                    py: '4',
                    bg: room.isLocked ? '#6b7280' : '#3b82f6',
                    color: 'white',
                    rounded: 'lg',
                    fontSize: 'xl',
                    fontWeight: 600,
                    cursor: room.isLocked ? 'not-allowed' : 'pointer',
                    opacity: room.isLocked ? 0.5 : 1,
                    _hover: room.isLocked ? {} : { bg: '#2563eb' },
                  })}
                >
                  {room.isLocked ? '🔒 Room Locked' : 'Join Room'}
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </PageWithNav>
  )
}